package com.dmlll.servlet;

import com.dmlll.demo.User;
import com.dmlll.service.UserService;
import com.dmlll.service.impl.UserServiceImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet(urlPatterns = "/checkName")
public class CheckNameServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        List<User> byUserName = userService.findByUserName(username);
        ServletOutputStream outputStream = resp.getOutputStream();
        if(byUserName.size() == 1) {
            JSONObject jsonObject = JSONObject.fromObject(byUserName.get(0));
            outputStream.print(String.valueOf(jsonObject));
        }else {
            JSONObject jsonObject = new JSONObject();
            outputStream.print(String.valueOf(jsonObject));
        }
    }
}
